import utils from './utils.js'
import constant from '@/const/index.js'

export function wechatAuth() {
  return new Promise((resolve, reject) => {
    let uuid = sessionStorage.getItem("uuid");
    let openId = sessionStorage.getItem("openId");
    let nickName = ''
    let unionid = ''
    let code = utils.getQueryString('code')
    if (uuid == undefined || uuid == null || uuid === '') {
      uuid = utils.generateUUID();
      sessionStorage.setItem('uuid', uuid);
    }
    if (code == null) {
      if (openId == undefined || openId == null || openId == '') {
        uni.request({
          url: constant.baseUrl + '/api/xmbz-order/OrdersPraise/open/auth',
          data: {
            url: window.location.href,
            uuid: sessionStorage.getItem("uuid")
          },
          method: "GET",
          success: (data) => {
            if (data.data.code == 200) {
              console.log(data.data.data.authUrl)
              window.location = data.data.data.authUrl;
            }
          },
          fail: () => {
            reject('CODE_ERROR_1001')
          }
        });
      }
    } else {
      nickName = sessionStorage.getItem("nickName");
      unionid = sessionStorage.getItem("unionid");
      if (openId == 'undefined' || openId == null || openId == '' || !unionid) {
        uni.request({
          url: constant.baseUrl + '/api/xmbz-order/OrdersPraise/open/openid',
          method: "GET",
          data: {
            code: code,
            uuid: sessionStorage.getItem("uuid"),
          },
          success: (data) => {
            if (data.data.data.openId == '') {
              window.location = window.location.href.split("?")[0];
            } else {
              console.log(data.data.data)
              sessionStorage.setItem('openId', data.data.data.openId);
              sessionStorage.setItem('nickName', data.data.data.user.nickname);
              sessionStorage.setItem('unionid', data.data.data.user.unionid);
              openId = data.data.data.openId;
              nickName = data.data.data.user.nickname;
              unionid = data.data.data.user.unionid;
              resolve({code, openId, nickName, unionid, uuid})
            }
          },
          fail: () => {
            reject('CODE_ERROR_1003')
          }
        });
      }
    }
  })
}

